/*
 * GeraPHPView.java
 */
package geraphp;

import br.gov.ce.sejus.util.arquivo.Arquivo;
import br.gov.ce.sejus.util.arquivo.Propriedades;
import br.gov.ce.sejus.util.tabela.Tabela;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.Task;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Properties;
import javax.swing.DefaultListModel;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 * The application's main frame.
 */
public class GeraPHPView extends FrameView {

    private Properties properties;
    private Propriedades prop;
    private StringBuilder avisos = new StringBuilder();
    private StringBuilder erro = new StringBuilder();
    private static String campoPk = "";
    private static ConexaoBD conexao = new ConexaoBD();

    public GeraPHPView(SingleFrameApplication app) {
        super(app);

        initComponents();
        obterDadosPropriedades();
        app.getMainFrame().setResizable(false);

        //Estado inicil das tabs. A tabela 1 deve está desabilitada.
        tabSistema.setSelectedIndex(0);
        tabSistema.setEnabledAt(1, false);
        tabMensagens.setSelectedIndex(0);

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
                if (avisos != null) {
                    txtResultados.setText(String.format("<div style='font-family:verdana; font-size:9px'>%s</div>", avisos));
                }
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {

            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String) (evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer) (evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        tabSistema = new javax.swing.JTabbedPane();
        pnmConfiguracoes = new javax.swing.JPanel();
        txtHost = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txtPorta = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        txtLogin = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        txtSenha = new javax.swing.JPasswordField();
        txtPasta = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jLabel12 = new javax.swing.JLabel();
        txtBD = new javax.swing.JTextField();
        jLabel13 = new javax.swing.JLabel();
        txtProjetoNome = new javax.swing.JTextField();
        chkAutoConect = new javax.swing.JCheckBox();
        chkEscolhaPk = new javax.swing.JCheckBox();
        jPanel4 = new javax.swing.JPanel();
        txtPastaDAO = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();
        txtPastaBean = new javax.swing.JTextField();
        jLabel15 = new javax.swing.JLabel();
        jLabel16 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        txtPastaConsultas = new javax.swing.JTextField();
        txtPastaForms = new javax.swing.JTextField();
        jLabel17 = new javax.swing.JLabel();
        txtPastaCss = new javax.swing.JTextField();
        jLabel18 = new javax.swing.JLabel();
        txtPastaImg = new javax.swing.JTextField();
        pnmTabelas = new javax.swing.JPanel();
        cmbEsquemas = new javax.swing.JComboBox();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tblAtributos = new javax.swing.JTable();
        jLabel8 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        lstTabelas = new javax.swing.JList();
        pnmTemplates = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtTemplateForm = new javax.swing.JTextField();
        btnPastaTemplateForm = new javax.swing.JButton();
        jLabel14 = new javax.swing.JLabel();
        txtTemplateConsulta = new javax.swing.JTextField();
        jButton3 = new javax.swing.JButton();
        jLabel19 = new javax.swing.JLabel();
        txtTemplateCSS = new javax.swing.JTextField();
        jButton4 = new javax.swing.JButton();
        btnConectar = new javax.swing.JButton();
        btnGeraCodigo = new javax.swing.JButton();
        tabMensagens = new javax.swing.JTabbedPane();
        jScrollPane4 = new javax.swing.JScrollPane();
        txtResultados = new javax.swing.JEditorPane();
        btnSalvarConfig = new javax.swing.JButton();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();
        cxaPastas = new javax.swing.JFileChooser();
        cxaArquivos = new javax.swing.JFileChooser();

        mainPanel.setName("mainPanel"); // NOI18N
        mainPanel.setLayout(null);

        tabSistema.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        tabSistema.setName("tabSistema"); // NOI18N
        tabSistema.setRequestFocusEnabled(false);

        pnmConfiguracoes.setName("pnmConfiguracoes"); // NOI18N
        pnmConfiguracoes.setLayout(null);

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(geraphp.GeraPHPApp.class).getContext().getResourceMap(GeraPHPView.class);
        txtHost.setText(resourceMap.getString("txtHost.text")); // NOI18N
        txtHost.setName("txtHost"); // NOI18N
        pnmConfiguracoes.add(txtHost);
        txtHost.setBounds(10, 22, 230, 28);

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N
        pnmConfiguracoes.add(jLabel2);
        jLabel2.setBounds(20, 0, 34, 16);

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N
        pnmConfiguracoes.add(jLabel3);
        jLabel3.setBounds(256, 0, 36, 16);

        txtPorta.setText(resourceMap.getString("txtPorta.text")); // NOI18N
        txtPorta.setName("txtPorta"); // NOI18N
        pnmConfiguracoes.add(txtPorta);
        txtPorta.setBounds(256, 22, 106, 28);

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N
        pnmConfiguracoes.add(jLabel4);
        jLabel4.setBounds(20, 60, 39, 16);

        txtLogin.setText(resourceMap.getString("txtLogin.text")); // NOI18N
        txtLogin.setName("txtLogin"); // NOI18N
        pnmConfiguracoes.add(txtLogin);
        txtLogin.setBounds(10, 84, 180, 28);

        jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
        jLabel5.setName("jLabel5"); // NOI18N
        pnmConfiguracoes.add(jLabel5);
        jLabel5.setBounds(200, 60, 41, 16);

        txtSenha.setText(resourceMap.getString("txtSenha.text")); // NOI18N
        txtSenha.setName("txtSenha"); // NOI18N
        pnmConfiguracoes.add(txtSenha);
        txtSenha.setBounds(200, 84, 160, 28);

        txtPasta.setText(resourceMap.getString("txtPasta.text")); // NOI18N
        txtPasta.setName("txtPasta"); // NOI18N
        pnmConfiguracoes.add(txtPasta);
        txtPasta.setBounds(380, 80, 330, 28);

        jLabel9.setText(resourceMap.getString("jLabel9.text")); // NOI18N
        jLabel9.setName("jLabel9"); // NOI18N
        pnmConfiguracoes.add(jLabel9);
        jLabel9.setBounds(380, 60, 90, 16);

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(geraphp.GeraPHPApp.class).getContext().getActionMap(GeraPHPView.class, this);
        jButton1.setAction(actionMap.get("salvarCaminhoPasta")); // NOI18N
        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton1MouseClicked(evt);
            }
        });
        pnmConfiguracoes.add(jButton1);
        jButton1.setBounds(710, 80, 40, 30);

        jLabel12.setText(resourceMap.getString("jLabel12.text")); // NOI18N
        jLabel12.setName("jLabel12"); // NOI18N
        pnmConfiguracoes.add(jLabel12);
        jLabel12.setBounds(20, 122, 37, 16);

        txtBD.setText(resourceMap.getString("txtBD.text")); // NOI18N
        txtBD.setName("txtBD"); // NOI18N
        pnmConfiguracoes.add(txtBD);
        txtBD.setBounds(12, 150, 350, 28);

        jLabel13.setText(resourceMap.getString("jLabel13.text")); // NOI18N
        jLabel13.setName("jLabel13"); // NOI18N
        pnmConfiguracoes.add(jLabel13);
        jLabel13.setBounds(380, 0, 105, 16);

        txtProjetoNome.setText(resourceMap.getString("txtProjetoNome.text")); // NOI18N
        txtProjetoNome.setName("txtProjetoNome"); // NOI18N
        pnmConfiguracoes.add(txtProjetoNome);
        txtProjetoNome.setBounds(380, 22, 380, 28);

        chkAutoConect.setText(resourceMap.getString("chkAutoConect.text")); // NOI18N
        chkAutoConect.setName("chkAutoConect"); // NOI18N
        pnmConfiguracoes.add(chkAutoConect);
        chkAutoConect.setBounds(10, 190, 350, 23);

        chkEscolhaPk.setText(resourceMap.getString("chkEscolhaPk.text")); // NOI18N
        chkEscolhaPk.setName("chkEscolhaPk"); // NOI18N
        pnmConfiguracoes.add(chkEscolhaPk);
        chkEscolhaPk.setBounds(10, 220, 300, 23);

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel4.border.title"))); // NOI18N
        jPanel4.setName("jPanel4"); // NOI18N
        jPanel4.setLayout(null);

        txtPastaDAO.setText(resourceMap.getString("txtPastaDAO.text")); // NOI18N
        txtPastaDAO.setName("txtPastaDAO"); // NOI18N
        jPanel4.add(txtPastaDAO);
        txtPastaDAO.setBounds(120, 50, 90, 28);

        jLabel10.setText(resourceMap.getString("jLabel10.text")); // NOI18N
        jLabel10.setName("jLabel10"); // NOI18N
        jPanel4.add(jLabel10);
        jLabel10.setBounds(20, 60, 40, 16);

        txtPastaBean.setText(resourceMap.getString("txtPastaBean.text")); // NOI18N
        txtPastaBean.setName("txtPastaBean"); // NOI18N
        jPanel4.add(txtPastaBean);
        txtPastaBean.setBounds(120, 20, 90, 28);

        jLabel15.setText(resourceMap.getString("jLabel15.text")); // NOI18N
        jLabel15.setName("jLabel15"); // NOI18N
        jPanel4.add(jLabel15);
        jLabel15.setBounds(220, 30, 80, 16);

        jLabel16.setText(resourceMap.getString("jLabel16.text")); // NOI18N
        jLabel16.setName("jLabel16"); // NOI18N
        jPanel4.add(jLabel16);
        jLabel16.setBounds(20, 90, 90, 16);

        jLabel11.setText(resourceMap.getString("jLabel11.text")); // NOI18N
        jLabel11.setName("jLabel11"); // NOI18N
        jPanel4.add(jLabel11);
        jLabel11.setBounds(20, 30, 94, 16);

        txtPastaConsultas.setText(resourceMap.getString("txtPastaConsultas.text")); // NOI18N
        txtPastaConsultas.setName("txtPastaConsultas"); // NOI18N
        jPanel4.add(txtPastaConsultas);
        txtPastaConsultas.setBounds(120, 80, 90, 28);

        txtPastaForms.setText(resourceMap.getString("txtPastaForms.text")); // NOI18N
        txtPastaForms.setName("txtPastaForms"); // NOI18N
        jPanel4.add(txtPastaForms);
        txtPastaForms.setBounds(300, 20, 80, 28);

        jLabel17.setText(resourceMap.getString("jLabel17.text")); // NOI18N
        jLabel17.setName("jLabel17"); // NOI18N
        jPanel4.add(jLabel17);
        jLabel17.setBounds(220, 60, 23, 16);

        txtPastaCss.setText(resourceMap.getString("txtPastaCss.text")); // NOI18N
        txtPastaCss.setName("txtPastaCss"); // NOI18N
        jPanel4.add(txtPastaCss);
        txtPastaCss.setBounds(300, 50, 80, 28);

        jLabel18.setText(resourceMap.getString("jLabel18.text")); // NOI18N
        jLabel18.setName("jLabel18"); // NOI18N
        jPanel4.add(jLabel18);
        jLabel18.setBounds(220, 90, 50, 16);

        txtPastaImg.setText(resourceMap.getString("txtPastaImg.text")); // NOI18N
        txtPastaImg.setName("txtPastaImg"); // NOI18N
        jPanel4.add(txtPastaImg);
        txtPastaImg.setBounds(300, 80, 80, 28);

        pnmConfiguracoes.add(jPanel4);
        jPanel4.setBounds(370, 120, 390, 130);

        tabSistema.addTab(resourceMap.getString("pnmConfiguracoes.TabConstraints.tabTitle"), pnmConfiguracoes); // NOI18N

        pnmTabelas.setName("pnmTabelas"); // NOI18N
        pnmTabelas.setLayout(null);

        cmbEsquemas.setName("cmbEsquemas"); // NOI18N
        cmbEsquemas.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cmbEsquemasItemStateChanged(evt);
            }
        });
        pnmTabelas.add(cmbEsquemas);
        cmbEsquemas.setBounds(20, 30, 181, 27);

        jLabel6.setText(resourceMap.getString("jLabel6.text")); // NOI18N
        jLabel6.setName("jLabel6"); // NOI18N
        pnmTabelas.add(jLabel6);
        jLabel6.setBounds(20, 10, 60, 16);

        jLabel7.setText(resourceMap.getString("jLabel7.text")); // NOI18N
        jLabel7.setName("jLabel7"); // NOI18N
        pnmTabelas.add(jLabel7);
        jLabel7.setBounds(20, 60, 45, 16);

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        tblAtributos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "PK", "Nome", "Tipo", "Tamanho", "É nulo"
            }
        ));
        tblAtributos.setName("tblAtributos"); // NOI18N
        tblAtributos.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane2.setViewportView(tblAtributos);

        pnmTabelas.add(jScrollPane2);
        jScrollPane2.setBounds(211, 32, 561, 220);

        jLabel8.setText(resourceMap.getString("jLabel8.text")); // NOI18N
        jLabel8.setName("jLabel8"); // NOI18N
        pnmTabelas.add(jLabel8);
        jLabel8.setBounds(210, 10, 51, 16);

        jScrollPane3.setName("jScrollPane3"); // NOI18N

        lstTabelas.setName("lstTabelas"); // NOI18N
        lstTabelas.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                lstTabelasValueChanged(evt);
            }
        });
        jScrollPane3.setViewportView(lstTabelas);

        pnmTabelas.add(jScrollPane3);
        jScrollPane3.setBounds(20, 81, 181, 170);

        tabSistema.addTab(resourceMap.getString("pnmTabelas.TabConstraints.tabTitle"), pnmTabelas); // NOI18N

        pnmTemplates.setName("pnmTemplates"); // NOI18N
        pnmTemplates.setLayout(null);

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N
        pnmTemplates.add(jLabel1);
        jLabel1.setBounds(10, 10, 149, 16);

        txtTemplateForm.setText(resourceMap.getString("txtTemplateForm.text")); // NOI18N
        txtTemplateForm.setName("txtTemplateForm"); // NOI18N
        pnmTemplates.add(txtTemplateForm);
        txtTemplateForm.setBounds(10, 30, 350, 28);

        btnPastaTemplateForm.setAction(actionMap.get("salvarCaminhoTemForm")); // NOI18N
        btnPastaTemplateForm.setText(resourceMap.getString("btnPastaTemplateForm.text")); // NOI18N
        btnPastaTemplateForm.setName("btnPastaTemplateForm"); // NOI18N
        pnmTemplates.add(btnPastaTemplateForm);
        btnPastaTemplateForm.setBounds(360, 30, 40, 28);

        jLabel14.setText(resourceMap.getString("jLabel14.text")); // NOI18N
        jLabel14.setName("jLabel14"); // NOI18N
        pnmTemplates.add(jLabel14);
        jLabel14.setBounds(10, 70, 160, 16);

        txtTemplateConsulta.setText(resourceMap.getString("txtTemplateConsulta.text")); // NOI18N
        txtTemplateConsulta.setName("txtTemplateConsulta"); // NOI18N
        pnmTemplates.add(txtTemplateConsulta);
        txtTemplateConsulta.setBounds(10, 90, 350, 28);

        jButton3.setAction(actionMap.get("salvarCaminhoTemCons")); // NOI18N
        jButton3.setText(resourceMap.getString("jButton3.text")); // NOI18N
        jButton3.setName("jButton3"); // NOI18N
        pnmTemplates.add(jButton3);
        jButton3.setBounds(360, 90, 40, 28);

        jLabel19.setText(resourceMap.getString("jLabel19.text")); // NOI18N
        jLabel19.setName("jLabel19"); // NOI18N
        pnmTemplates.add(jLabel19);
        jLabel19.setBounds(10, 130, 140, 16);

        txtTemplateCSS.setText(resourceMap.getString("txtTemplateCSS.text")); // NOI18N
        txtTemplateCSS.setName("txtTemplateCSS"); // NOI18N
        pnmTemplates.add(txtTemplateCSS);
        txtTemplateCSS.setBounds(10, 150, 350, 28);

        jButton4.setAction(actionMap.get("salvarCaminhoTempCss")); // NOI18N
        jButton4.setText(resourceMap.getString("jButton4.text")); // NOI18N
        jButton4.setName("jButton4"); // NOI18N
        pnmTemplates.add(jButton4);
        jButton4.setBounds(360, 150, 40, 28);

        tabSistema.addTab(resourceMap.getString("pnmTemplates.TabConstraints.tabTitle"), pnmTemplates); // NOI18N

        mainPanel.add(tabSistema);
        tabSistema.setBounds(10, 10, 790, 310);

        btnConectar.setAction(actionMap.get("conectarBD")); // NOI18N
        btnConectar.setText(resourceMap.getString("btnConectar.text")); // NOI18N
        btnConectar.setName("btnConectar"); // NOI18N
        mainPanel.add(btnConectar);
        btnConectar.setBounds(30, 320, 140, 30);

        btnGeraCodigo.setAction(actionMap.get("gerarArquivosPHP")); // NOI18N
        btnGeraCodigo.setText(resourceMap.getString("btnGeraCodigo.text")); // NOI18N
        btnGeraCodigo.setName("btnGeraCodigo"); // NOI18N
        mainPanel.add(btnGeraCodigo);
        btnGeraCodigo.setBounds(180, 320, 150, 30);

        tabMensagens.setBackground(resourceMap.getColor("tabMensagens.background")); // NOI18N
        tabMensagens.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        tabMensagens.setName("tabMensagens"); // NOI18N

        jScrollPane4.setName("jScrollPane4"); // NOI18N

        txtResultados.setContentType(resourceMap.getString("txtResultados.contentType")); // NOI18N
        txtResultados.setEditable(false);
        txtResultados.setName("txtResultados"); // NOI18N
        jScrollPane4.setViewportView(txtResultados);

        tabMensagens.addTab(resourceMap.getString("jScrollPane4.TabConstraints.tabTitle"), jScrollPane4); // NOI18N

        mainPanel.add(tabMensagens);
        tabMensagens.setBounds(10, 360, 790, 200);

        btnSalvarConfig.setAction(actionMap.get("salvarConfiguracoes")); // NOI18N
        btnSalvarConfig.setText(resourceMap.getString("btnSalvarConfig.text")); // NOI18N
        btnSalvarConfig.setName("btnSalvarConfig"); // NOI18N
        mainPanel.add(btnSalvarConfig);
        btnSalvarConfig.setBounds(630, 320, 160, 28);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        org.jdesktop.layout.GroupLayout statusPanelLayout = new org.jdesktop.layout.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(statusPanelSeparator, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 803, Short.MAX_VALUE)
            .add(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(statusMessageLabel)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 607, Short.MAX_VALUE)
                .add(progressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(statusPanelLayout.createSequentialGroup()
                .add(statusPanelSeparator, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(statusMessageLabel)
                    .add(statusAnimationLabel)
                    .add(progressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(3, 3, 3))
        );

        cxaPastas.setDialogTitle(resourceMap.getString("cxaPastas.dialogTitle")); // NOI18N
        cxaPastas.setDialogType(javax.swing.JFileChooser.CUSTOM_DIALOG);
        cxaPastas.setFileSelectionMode(javax.swing.JFileChooser.FILES_AND_DIRECTORIES);
        cxaPastas.setName("cxaPastas"); // NOI18N

        cxaArquivos.setName("cxaArquivos"); // NOI18N

        setComponent(mainPanel);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents

    private void obterDadosPropriedades() {

        String caminhoReal = new File(".").getAbsolutePath().replace(".", "");

        caminhoReal += "param.properties";
        if (!new File(caminhoReal).exists()) {

            StringBuilder sb = new StringBuilder();

            sb.append(""
                    + "# Parâmetros do sistema de geração de código em php\n\n"
                    + "#Configurações do banco de dados\n"
                    + "host=172.18.4.24\n\n"
                    + "porta=5432\n"
                    + "login=postgres\n"
                    + "senha=admin\n"
                    + "banco=banco\n\n"
                    + "#Dados do projeto\n"
                    + "projeto=phpGen\n"
                    + "pasta=/var/usr\n"
                    + "pastaDao=dao\n"
                    + "pastaBean=bean\n"
                    + "autoconect=true"
                    + "perguntapk=false");

            new Arquivo().criarArquivo(caminhoReal, sb.toString());
        }

        this.prop = new Propriedades(caminhoReal, true);

        this.properties = prop.carregarPropriedades();

        txtBD.setText(properties.getProperty("banco"));
        txtHost.setText(properties.getProperty("host"));
        txtLogin.setText(properties.getProperty("login"));
        txtPasta.setText(properties.getProperty("pasta"));
        txtPastaBean.setText(properties.getProperty("pastaBean"));
        txtPastaDAO.setText(properties.getProperty("pastaDao"));
        txtPorta.setText(properties.getProperty("porta"));
        txtProjetoNome.setText(properties.getProperty("projeto"));
        txtSenha.setText(properties.getProperty("senha"));
        chkAutoConect.setSelected(Boolean.parseBoolean(properties.getProperty("autoconect")));
        chkEscolhaPk.setSelected(Boolean.parseBoolean(properties.getProperty("perguntapk")));

        if (chkAutoConect.isSelected()) {
            btnConectar.doClick();
        }
    }

    private void cmbEsquemasItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cmbEsquemasItemStateChanged
        popularTabelas();
    }//GEN-LAST:event_cmbEsquemasItemStateChanged

    private void popularTabelas() {
        lstTabelas.setModel(new javax.swing.AbstractListModel() {

            String[] strings = conexao.obterTabelas(cmbEsquemas.getSelectedItem().toString());

            @Override
            public int getSize() {
                return strings.length;
            }

            @Override
            public Object getElementAt(int i) {
                return strings[i];
            }
        });
    }
    ArrayList listaDeCampos = new ArrayList();

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked
    }//GEN-LAST:event_jButton1MouseClicked

    private void lstTabelasValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_lstTabelasValueChanged
        Tabela tabela = new Tabela();
        ArrayList listaCampos = conexao.obterCampos(lstTabelas.getSelectedValue().toString());

        String[] colunas = {"PK", "Nome", "Tipo", "Tamanho", "É nulo"};

        listaDeCampos = listaCampos;

        tblAtributos = tabela.criarTabela(tblAtributos, colunas, listaCampos);
}//GEN-LAST:event_lstTabelasValueChanged

    @Action
    public Task conectarBD() {
        return new ConectarBDTask(getApplication());
    }

    private class ConectarBDTask extends org.jdesktop.application.Task<Object, Void> {

        ConectarBDTask(org.jdesktop.application.Application app) {

            super(app);
        }

        @Override
        protected Object doInBackground() {
            try {
                if (!conexao.estaConectado()) {

                    btnConectar.setText("Desconectar...");
                    conectarBd();
                } else {

                    conexao.desconectarBD();
                    btnConectar.setText("Conectar...");
                    avisos.append("Desconectado o banco de dados.<br/>");

                    String[] colunas = {"PK", "Nome", "Tipo", "Tamanho", "É nulo"};
                    tblAtributos.setModel(new DefaultTableModel(colunas, 0));
                    lstTabelas.setModel(new DefaultListModel());
                    cmbEsquemas.setModel(new javax.swing.DefaultComboBoxModel());
                    btnGeraCodigo.setEnabled(false);

                    tabSistema.setSelectedIndex(0);
                    tabSistema.setEnabledAt(1, false);

                    tabMensagens.setSelectedIndex(0);

                }
            } catch (Exception ex) {
                erro.append("Problemas de conexão com o banco de dados. <br/>");
                tabMensagens.setSelectedIndex(1);
            } finally {
                txtResultados.setText(String.format("<div style='font-family:verdana; font-size:9px'>%s</div>", avisos));
            }
            return null;  // return your result
        }

        @Override
        protected void succeeded(Object result) {
            // Runs on the EDT.  Update the GUI based on
            // the result computed by doInBackground().
        }
    }

    private void conectarBd() {
        try {
            tabSistema.setSelectedIndex(1);
            tabSistema.setEnabledAt(1, true);
            conexao.conectarBD(txtHost.getText(), txtLogin.getText(),
                    txtSenha.getText(), txtBD.getText());
            avisos.append("Conectado ao banco de dados.<br/>");

            Object[] listaEsquema = conexao.obterEsquemas();

            cmbEsquemas.setModel(new javax.swing.DefaultComboBoxModel(listaEsquema));

            popularTabelas();

            btnGeraCodigo.setEnabled(true);

        } catch (Exception ex) {
            erro.append(ex.getMessage());
        }
    }

    @Action
    public Task gerarArquivosPHP() {
        return new GerarArquivosPHPTask(getApplication());
    }

    private class GerarArquivosPHPTask extends org.jdesktop.application.Task<Object, Void> {

        GerarArquivosPHPTask(org.jdesktop.application.Application app) {
            // Runs on the EDT.  Copy GUI state that
            // doInBackground() depends on from parameters
            // to GerarArquivosPHPTask fields, here.
            super(app);
        }

        @Override
        protected Object doInBackground() {

            if (lstTabelas.getSelectedValues().length < 1) {
                JOptionPane.showMessageDialog(null, "Selecione pelo menos uma tabela na lista de tabelas.");
            } else {

                Long tempoIni = System.currentTimeMillis();
                PersistenceFactory factory = new PersistenceFactory(listaDeCampos,
                        txtBD.getText(), txtHost.getText(), txtPorta.getText(),
                        txtLogin.getText(), txtSenha.getText(), txtPasta.getText(),
                        txtProjetoNome.getText(), txtPastaBean.getText(),
                        txtPastaDAO.getText());

                Object[] nomesDastabelas = lstTabelas.getSelectedValues();

                avisos.append("Gerando código para as tabelas: <br/>");
                boolean ok = false;
                boolean ok2 = false;

                String strFinal = ", ";
                int i = 0;
                boolean ocorreuErro = false;
                EscolhaPK.conexao = conexao;
                String manualPk = null;
                for (Object nomeTabela : nomesDastabelas) {

                    factory.setListaAtributos(conexao.obterCampos(nomeTabela.toString()));

                    ok = factory.gerarCodigo(nomeTabela.toString());

                    if (!ok && chkEscolhaPk.isSelected()) {

                        EscolhaPK.nomeTabela = nomeTabela.toString();
                        mostraEscolhaPk();

                        manualPk = "<span style'color:green;'> (PK: " + EscolhaPK.nomeAtributo + ")</span>";
                        if (EscolhaPK.nomeAtributo != null && !EscolhaPK.nomeAtributo.isEmpty()) {
                            factory.setCampoPk(EscolhaPK.nomeAtributo);
                            EscolhaPK.nomeAtributo = "";
                        }

                        ok2 = factory.gerarCodigo(nomeTabela.toString());
                    } else {
                        ok2 = ok;
                    }


                    if (i == nomesDastabelas.length - 1) {
                        strFinal = ".";
                    }

                    if (ok2) {
                        avisos.append(nomeTabela.toString() + manualPk + strFinal);
                    } else {
                        avisos.append("<span style='color:red;'>").append(nomeTabela.toString()).append("</span>").append(strFinal);
                        erro.append(factory.getMsgErro()).append("<br/>");
                        ocorreuErro = true;
                    }
                    manualPk = "";
                    i++;
                }

                Long tempoFim = System.currentTimeMillis();
                avisos.append("<br/>Tempo de geração: ").append(tempoFim - tempoIni).append("ms<br/>");
                txtResultados.setText(String.format("<div style='font-family:verdana; font-size:9px'>%s</div>", avisos));
            }

            txtResultados.setText(String.format("<div style='color:red;font-family:verdana; font-size:9px'>%s</div>", erro));
            return null;  // return your result
        }

        @Override
        protected void succeeded(Object result) {
            // Runs on the EDT.  Update the GUI based on
            // the result computed by doInBackground().
        }
    }

    public void mostraEscolhaPk() {
        if (escolhaPk == null) {
            JFrame mainFrame = GeraPHPApp.getApplication().getMainFrame();
            escolhaPk = new EscolhaPK(mainFrame, true);
            escolhaPk.setLocationRelativeTo(mainFrame);
        }

        GeraPHPApp.getApplication().show(escolhaPk);
    }

    @Action
    public void salvarCaminhoPasta() {
        cxaPastas.showOpenDialog(null);
        try {
            txtPasta.setText(cxaPastas.getCurrentDirectory().getCanonicalPath().toString() + File.separator);
        } catch (IOException ex) {
            Logger.getLogger(GeraPHPView.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Action
    public void selecionarTabelas() {
        //lstTabelas.setSelectionModel(new Selection);
    }

    @Action
    public void salvarCaminhoTemForm() {
        cxaArquivos.showOpenDialog(null);
        try {
            txtTemplateForm.setText(cxaArquivos.getSelectedFile().getCanonicalPath());
        } catch (IOException ex) {
            Logger.getLogger(GeraPHPView.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Action
    public void salvarCaminhoTemCons() {
        cxaArquivos.showOpenDialog(null);
        try {
            txtTemplateConsulta.setText(cxaArquivos.getSelectedFile().getCanonicalPath());
        } catch (IOException ex) {
            Logger.getLogger(GeraPHPView.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Action
    public Task salvarConfiguracoes() {
        return new SalvarConfiguracoesTask(getApplication());
    }

    private class SalvarConfiguracoesTask extends org.jdesktop.application.Task<Object, Void> {

        SalvarConfiguracoesTask(org.jdesktop.application.Application app) {
            // Runs on the EDT.  Copy GUI state that
            // doInBackground() depends on from parameters
            // to SalvarConfiguracoesTask fields, here.
            super(app);
        }

        @Override
        protected Object doInBackground() {
            properties.setProperty("banco", txtBD.getText());
            properties.setProperty("host", txtHost.getText());
            properties.setProperty("login", txtLogin.getText());
            properties.setProperty("pasta", txtPasta.getText());
            properties.setProperty("pastaBean", txtPastaBean.getText());
            properties.setProperty("pastaDao", txtPastaDAO.getText());
            properties.setProperty("porta", txtPorta.getText());
            properties.setProperty("projeto", txtProjetoNome.getText());
            properties.setProperty("senha", txtSenha.getText());
            properties.setProperty("autoconect", Boolean.toString(chkAutoConect.isSelected()));
            properties.setProperty("perguntapk", Boolean.toString(chkEscolhaPk.isSelected()));

            prop.atualizarPropriedades(properties);
            
            return null;  // return your result
        }

        @Override
        protected void succeeded(Object result) {
            // Runs on the EDT.  Update the GUI based on
            // the result computed by doInBackground().
        }
    }

    @Action
    public void salvarCaminhoTempCss() {
        cxaArquivos.showOpenDialog(null);
        try {
            txtTemplateCSS.setText(cxaArquivos.getSelectedFile().getCanonicalPath());
        } catch (IOException ex) {
            Logger.getLogger(GeraPHPView.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnConectar;
    private javax.swing.JButton btnGeraCodigo;
    private javax.swing.JButton btnPastaTemplateForm;
    private javax.swing.JButton btnSalvarConfig;
    private javax.swing.JCheckBox chkAutoConect;
    private javax.swing.JCheckBox chkEscolhaPk;
    private javax.swing.JComboBox cmbEsquemas;
    private javax.swing.JFileChooser cxaArquivos;
    private javax.swing.JFileChooser cxaPastas;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel18;
    private javax.swing.JLabel jLabel19;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JList lstTabelas;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JPanel pnmConfiguracoes;
    private javax.swing.JPanel pnmTabelas;
    private javax.swing.JPanel pnmTemplates;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    private javax.swing.JTabbedPane tabMensagens;
    private javax.swing.JTabbedPane tabSistema;
    private javax.swing.JTable tblAtributos;
    private javax.swing.JTextField txtBD;
    private javax.swing.JTextField txtHost;
    private javax.swing.JTextField txtLogin;
    private javax.swing.JTextField txtPasta;
    private javax.swing.JTextField txtPastaBean;
    private javax.swing.JTextField txtPastaConsultas;
    private javax.swing.JTextField txtPastaCss;
    private javax.swing.JTextField txtPastaDAO;
    private javax.swing.JTextField txtPastaForms;
    private javax.swing.JTextField txtPastaImg;
    private javax.swing.JTextField txtPorta;
    private javax.swing.JTextField txtProjetoNome;
    private javax.swing.JEditorPane txtResultados;
    private javax.swing.JPasswordField txtSenha;
    private javax.swing.JTextField txtTemplateCSS;
    private javax.swing.JTextField txtTemplateConsulta;
    private javax.swing.JTextField txtTemplateForm;
    // End of variables declaration//GEN-END:variables
    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;
    private JDialog escolhaPk;
}
